package com.jn.erp.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.utils.MessageUtils;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.entity.LoginUser;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.sysservice.SysRoleService;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.security.sysservice.enums.UserStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户验证处理
 *
 * @author jn
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //用于区分web和app (web端需要选中机构后登录 app 进入平台默认查找第一个机构#0表示app)
        Long  orgId =Long.valueOf(getLastHashValue(username));
        String newUsername=getBeferHashValue(username);
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.and(qwr-> qwr.eq("name", newUsername).or().eq("mobile",newUsername));
        qw.eq("state", 0);
        SysUser user = userService.getOne(qw);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", newUsername);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getState())) {
            log.info("登录用户：{} 已被删除.", newUsername);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getState())) {
            log.info("登录用户：{} 已被停用.", newUsername);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        passwordService.validate(user);

        user.setOrgId(orgId);
        if(orgId==0l){
            List<SysRole> rolesByUser = roleService.getRolesByUser(user.getId());
            if (!rolesByUser.isEmpty()) {
                user.setRoles(rolesByUser);
            }
        }else{
            List<SysRole> rolesByUser = roleService.getRolesByOrgUser(user.getId(),orgId);
            if (!rolesByUser.isEmpty()) {
                user.setRoles(rolesByUser);
            }
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
//        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        LoginUser loginUser = new LoginUser(user.getId(), user, permissionService.getMenuPermission(user));
        loginUser.setOrgId(user.getOrgId());
        return loginUser;
    }


    public UserDetails loadUserByUsernameNoPassword(String username) throws UsernameNotFoundException {

        QueryWrapper<SysUser> qw = new QueryWrapper<>();
//        qw.eq("name", username);
        qw.and(qwr-> qwr.eq("name", username).or().eq("mobile",username));
        qw.eq("state", 0);
        SysUser user = userService.getOne(qw);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getState())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getState())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        List<SysRole> rolesByUser = roleService.getRolesByUser(user.getId());
        if (!rolesByUser.isEmpty()) {
            user.setRoles(rolesByUser);
        }
        return createLoginUser(user);
    }

    public static String getLastHashValue(String str) {
        int lastIndex = str.lastIndexOf('#');
        if (lastIndex != -1) {
            return str.substring(lastIndex + 1);
        }
        return str; // 如果没有#，返回原字符串
    }
    public static String getBeferHashValue(String str) {
        int lastIndex = str.lastIndexOf('#');
        if (lastIndex != -1) {
            return str.substring(0, lastIndex);
        }
        return str; // 如果没有#，返回原字符串
    }
}
